<?php


namespace app\common\model;

use app\common\model\Member;
use think\Model;
use think\Db;
use app\common\model\Device;
use app\common\model\Park;
use app\common\model\Car;

class YinuoOrder extends Model
{
    protected $table = "store_yinuo_order";

    //一诺订单
    public function order_list($param){
        $page = $param['page']??1;
        $page = ($page-1)*10;
        $where = [];
        $w = "";
        if(!empty($param['status'])){
            if($param['status']==1||$param['status']==2){
                $where['status'] = $param['status'];
            }elseif ($param['status']==3){
                $w = "status in (3,4)";
            }elseif ($param['status']==4){
                $w = "status in (5,6)";
            }
        }
        if(!empty($param['type'])){
            $where['type'] = $param['type'];
        }

        $user_id = $param['user_id'];

        $list = self::where('user_id',"in",$user_id)->where($where)->where($w)->order("id desc")->limit($page,10)->select();
        $Device = new Device();
        $Park = new Park();
        $Car = new Car();

        foreach($list as $k =>&$v){
            $v['device'] = $Device::where(['id'=>$v['device_id']])->find();
            $v['park'] = $Park::where(['id'=>$v['park_id']])->find();
            $v['member'] = Member::where(["id"=>$v['member_id']])->find();
            $v['station'] = Db::table("store_power_station")->where(['id'=>$v['station_id']])->find();
            $v['comment'] = Db::table("store_station_comment")->where(['station_id'=>$v['station_id'],"order_id"=>$v['id']])->find();

            $v['car'] = $Car::where(['id'=>$v['car_id']])->find();
            $v['car_tel'] = $v['member']['phone'];

            $time = time();
            $v['use_time'] = (int)(($time-strtotime($v['start_time']))/60);
            $v['use_time2'] = (int)((strtotime($v['paid_time'])-strtotime($v['start_time']))/60);
            $hour = ceil($v['use_time']/60);

            if($v['type']==2){
                if($v['status']<5){
                    $v['park_price'] = sprintf('%.2f',($hour*$v['park']['price']));
                }
            }else{
                if($v['status']<5){
                    $v['park_price'] = sprintf('%.2f',($hour*$v['park']['price']));

                    $device = Db::table("store_device")->where(['id'=>$v['device_id']])->find();
                    $free_park_hour = $device['free_park_hour']??0;
                    $free_park_time = $free_park_hour*3600;
                    $park_time = time()-strtotime($v['start_time']);
                    if($free_park_time>$park_time){
                        $v['park_price'] = 0;
                        if($v['charging_capacity']<20){
                            $xiaoshi = ceil($park_time/3600);
                            $v['park_price'] = sprintf('%.2f',$xiaoshi*1);
                        }
                    }else{
                        $cha = $park_time-$free_park_time;
                        $xiaoshi = ceil($cha/3600);
                        $v['park_price'] = sprintf('%.2f',$xiaoshi*$v['park']['price']);
                    }


                }
            }
            $v['floor'] = sprintf('%.2f',$v['use_time']/60);

            if($v['status']==4){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charging_amount']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }elseif ($v['status']==5){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charge_price']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }elseif ($v['status']==6){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charge_price']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }else{
                $v['du'] = 0;
            }
        }
        return $list;
    }


    //创建订单
    public function create_order($param){
        $param['shuxing'] = $param['shuxing']??'order';
        $param['order_no'] = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $param['create_at'] = date('Y-m-d H:i:s');
        if($param['type']==1){
            if(empty($param['device_id'])){
                return '设备桩id不能为空';
            }else{
                $device = Db::table("store_device")->where(['id'=>$param['device_id']])->find();
                if($device) {
                    if ($device['status'] == 1) {
                        if ($device) {
                            $param['station_id'] = $device['station_id'];
                            $param['park_id'] = $device['park_id'];
                            $param['user_id'] = $device['user_id'];
                            Db::table("store_device")->where(['id' => $param['device_id']])->update(['status' => 3]);
                            Db::table("store_park")->where(['id' => $device['park_id']])->update(['status' => 3]);
                            Db::table("store_device")->where(['park_id' => $device['park_id']])->update(['status' => 3]);

                        }
                    } elseif ($device['status'] == 2) { //2故障  3被占用  4停用
                        return '设备桩故障';
                    } elseif ($device['status'] == 3) {
                        return '设备桩被占用';
                    } elseif ($device['status'] == 4) {
                        return '设备桩已停用';
                    } else {
                        return '系统错误';
                    }
                }else {
                    return '系统错误';
                }
            }
        }else{
            $device = Db::table("store_park")->where(['id'=>$param['device_id']])->find();
            if($device){
                if($device['status']==1) {

                    $have = Db::table("store_device")->where("status!=1")->where(['park_id'=>$device['id']])->find();
                    if(!empty($have)){
                        return '电桩被占用，此车位不能预约哦';
                    }


                    $param['station_id'] = $device['station_id'];
                    $param['park_id'] = $device['id'];
                    $param['user_id'] = $device['user_id'];
                    $param['device_id'] = 0;

                    Db::table("store_park")->where(['id' => $device['id']])->update(['status' => 3]);
                    Db::table("store_device")->where(['park_id' => $device['id']])->update(['status' => 3]);


                }elseif ($device['status']==2){ //2故障  3被占用  4停用
                    return '车位故障';
                }elseif ($device['status']==3){
                    return '车位被占用';
                }elseif ($device['status']==4){
                    return '车位已停用';
                }else{
                    return '系统错误';
                }
            }else{
                return '系统错误';
            }
        }


        $insertGetId = self::insertGetId($param);
        if($param['shuxing']=='self'){
            Db::table("store_yinuo_order")->where(['id'=>$insertGetId])->update(['status'=>3,'start_time'=>date('Y-m-d H:i:s'),'charge_start_time'=>date('Y-m-d H:i:s'),"is_out"=>1]);
        }

        return 1;
    }


    //我的订单
    public function my_order($param){
        $param['shuxing'] = $param['shuxing']??'order';
        $arr = [
            '0:00~0:30','0:30~1:00','1:00~1:30','1:30~2:00','2:00~2:30','2:30~3:00','3:00~3:30','3:30~4:00','4:00~4:30','4:30~5:00',
            '5:00~5:30','5:30~6:00','6:00~6:30','6:30~7:00','7:00~7:30','7:30~8:00','8:00~8:30','8:30~9:00',
            '9:00~9:30','9:30~10:00','10:00~10:30','10:30~11:00','11:00~11:30','11:30~12:00','12:00~12:30','12:30~13:00',
            '13:00~13:30','13:30~14:00','14:00~14:30','14:30~15:00','15:00~15:30','15:30~16:00','16:00~16:30','16:30~17:00',
            '17:00~17:30','17:30~18:00','18:00~18:30','18:30~19:00','19:00~19:30','19:30~20:00','20:00~20:30','20:30~21:00',
            '21:00~21:30','21:30~22:00','22:00~22:30','22:30~23:00','23:00~23:30','23:30~24:00'
        ];
        $page = $param['page']??1;
        $page = ($page-1)*10;
        $where = "";
        //1预约充电/停车   2放行后 已预约   3充电/停车中  4充电/停车完成（待支付）  5已支付（待评论） 6已评论（全部完成）
        if($param['menu_type']){
            if($param['menu_type']==1){
                $where = "status in (1,2)";
            }
            if($param['menu_type']==2){
                $where = "status in (3)";
            }
            if($param['menu_type']==3){
                $where = "status in (4)";
            }
            if($param['menu_type']==4){
                $where = "status in (5)";
            }
            if($param['menu_type']==5){
                $where = "status in (6)";
            }
        }
        if($param['shuxing']=='self'){
            $list =  self::where(['member_id'=>$param['member_id']])->where($where)->where("shuxing='self'")->where("delete_time is null")->order("id desc")->select();
        }else{
            $list =  self::where(['member_id'=>$param['member_id']])->where($where)->where("shuxing='order'")->where("delete_time is null")->order("id desc")->limit($page,10)->select();
        }
        $array = [];
        foreach ($list as $k =>&$v){
            //1预约充电/停车   2放行后 已预约   3充电/停车中  4充电/停车完成（待支付）  5已支付（待评论） 6已评论（全部完成）
            if($v['status']==1){
                $v['status_name'] = '订单状态：预约充电/停车';
            }
            if($v['status']==2){
                $v['status_name'] = '订单状态：放行后 已预约';
            }
            if($v['status']==3){
                $v['status_name'] = '订单状态：充电/停车中';
            }
            if($v['status']==4){
                $v['status_name'] = '订单状态：充电/停车完成（待支付）';
            }
            if($v['status']==5){
                $v['status_name'] = '订单状态：已支付（待评论）';
            }
            if($v['status']==6){
                $v['status_name'] = '订单状态：已评论（全部完成）';
            }

            if($v['type']==1){
                $v['type_name'] = '预约充电';
            }
            if($v['type']==2){
                $v['type_name'] = '预约停车';
            }

            $v['member'] = Db::table("store_member")->where(['id'=>$v['member_id']])->find();
            $v['device'] = Db::table("store_device")->where(['id'=>$v['device_id']])->find();
            $v['park'] = Db::table("store_park")->where(['id'=>$v['park_id']])->find();
            $v['station'] = Db::table("store_power_station")->where(['id'=>$v['station_id']])->find();
            $v['user'] = Db::table("store_member")->where(['id'=>$v['user_id']])->find();
            $v['car'] = Db::table("store_car")->where(['id'=>$v['car_id']])->find();
            $v['car_tel'] = $v['member']['phone'];

            $v['time'] = strtotime($v['create_at']);
            $v['jiezhi'] = $v['time']+1800;

            $time = time();
            $v['daojishi'] = $v['jiezhi'] - $time;
            if($v['daojishi']<0){
                $v['daojishi'] = 0;
            }

            $v['use_time'] = (int)(($time-strtotime($v['start_time']))/60);
            $v['use_time2'] = (int)((strtotime($v['paid_time'])-strtotime($v['start_time']))/60);
            $hour = ceil($v['use_time']/60);

            if($v['type']==2){
                $v['park_price_wait'] = sprintf('%.2f',($hour*$v['park']['price']));
            }else{
                $v['park_price_wait'] = sprintf('%.2f',($hour*$v['park']['price']));

                $device = Db::table("store_device")->where(['id'=>$v['device_id']])->find();
                $free_park_hour = $device['free_park_hour']??0;
                $free_park_time = $free_park_hour*3600;
                $park_time = time()-strtotime($v['start_time']);
                if($free_park_time>$park_time){
                    $v['park_price_wait'] = 0;
                    if($v['charging_capacity']<20){
                        $xiaoshi = ceil($park_time/3600);
                        $v['park_price_wait'] = sprintf('%.2f',$xiaoshi*1);
                    }
                }else{
                    $cha = $park_time-$free_park_time;
                    $xiaoshi = ceil($cha/3600);
                    $v['park_price_wait'] = sprintf('%.2f',$xiaoshi*$v['park']['price']);
                }
            }


            if($v['status']==4){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charging_amount']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }elseif ($v['status']==5){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charge_price']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }elseif ($v['status']==6){
                if($v['charging_capacity']>0){
                    $v['du'] = sprintf('%.2f',$v['charge_price']/$v['charging_capacity']);
                }else{
                    $v['du'] = 0;
                }
            }else{
                $v['du'] = 0;
            }


            if($v['device']){
                $v['cost_price1'] = '尖电价：'.sprintf('%.4f',$v['device']['price']).'元/度 <br>服务费：'.sprintf('%.4f',$v['device']['service_price']).'元/度 <br>';
                $cost_time1 = '';
                $v['cost_price2'] = '峰电价：'.sprintf('%.4f',$v['device']['price2']).'元/度 <br>服务费：'.sprintf('%.4f',$v['device']['service_price2']).'元/度 <br>';
                $cost_time2 = '';
                $v['cost_price3'] = '平电价：'.sprintf('%.4f',$v['device']['price3']).'元/度 <br>服务费：'.sprintf('%.4f',$v['device']['service_price3']).'元/度 <br>';
                $cost_time3 = '';
                $v['cost_price4'] = '谷电价：'.sprintf('%.4f',$v['device']['price4']).'元/度 <br>服务费：'.sprintf('%.4f',$v['device']['service_price4']).'元/度 <br>';
                $cost_time4 = '';
                $cost_model = json_decode($v['device']['cost_model'],true);
                if($cost_model) {
                    foreach ($cost_model as $kk => &$vv) {
                        if ($vv == 1) {
                            $cost_time1 .= $arr[$kk] . ' ';
                        }
                        if ($vv == 2) {
                            $cost_time2 .= $arr[$kk] . ' ';
                        }
                        if ($vv == 3) {
                            $cost_time3 .= $arr[$kk] . ' ';
                        }
                        if ($vv == 4) {
                            $cost_time4 .= $arr[$kk] . ' ';
                        }
                    }

                    $v['cost_price1'] .= ' 时段：' . $cost_time1;
                    $v['cost_price2'] .= ' 时段：' . $cost_time2;
                    $v['cost_price3'] .= ' 时段：' . $cost_time3;
                    $v['cost_price4'] .= ' 时段：' . $cost_time4;
                }else{
                    $v['cost_price1'] = ' ';
                    $v['cost_price2'] = ' ';
                    $v['cost_price3'] = ' ';
                    $v['cost_price4'] = ' ';
                }
            }else{
                $v['cost_price1'] = ' ';
                $v['cost_price2'] = ' ';
                $v['cost_price3'] = ' ';
                $v['cost_price4'] = ' ';
            }

        }

        return $list;
    }


    //我的订单
    public function master_order($param){
        $where = "";
        //1预约充电/停车   2放行后 已预约   3充电/停车中  4充电/停车完成（待支付）  5已支付（待评论） 6已评论（全部完成）
        if($param['menu_type']){
            if($param['menu_type']==1){
                $where = "status in (1)";
            }
            if($param['menu_type']==3){
                $where = "status in (2,3,4)";
            }
            if($param['menu_type']==4){
                $where = "status in (5,6) and is_out=0";
            }
        }

        $user_id = $param['user_id'];
        $user_list = Db::table("store_power_station")->field("user_id")->where(['parent_id'=>$user_id])->select();
        $arr = [$user_id];
        foreach ($user_list as $k =>$v){
            if(!in_array($v['user_id'],$arr)){
                array_push($arr,$v['user_id']);
            }
        }
        $str = '';
        if($arr){
            $str = implode(',',$arr);
        }

        $list =  self::where("user_id","in",$str)->where($where)->where("delete_time is null")->order("id desc")->select();

        foreach ($list as $k =>&$v){
            if($v['status']==1){
                $v['status_name'] = '订单状态：预约充电/停车';   //可进场
            }
            if($v['status']==2){
                $v['status_name'] = '订单状态：放行后 已预约';
            }
            if($v['status']==3){
                $v['status_name'] = '订单状态：充电/停车中';
            }
            if($v['status']==4){
                $v['status_name'] = '订单状态：充电/停车完成（待支付）';
            }
            if($v['status']==5){
                $v['status_name'] = '订单状态：已支付（待评论）'; //可放行
            }
            if($v['status']==6){
                $v['status_name'] = '订单状态：已评论（全部完成）'; //可放行
            }

            if($v['type']==1){
                $v['type_name'] = '预约充电';
            }
            if($v['type']==2){
                $v['type_name'] = '预约停车';
            }

            $v['member'] = Db::table("store_member")->where(['id'=>$v['member_id']])->find();
            $v['device'] = Db::table("store_device")->where(['id'=>$v['device_id']])->find();
            $v['park'] = Db::table("store_park")->where(['id'=>$v['park_id']])->find();
            $v['station'] = Db::table("store_power_station")->where(['id'=>$v['station_id']])->find();
            $v['user'] = Db::table("store_member")->where(['id'=>$v['user_id']])->find();
            $v['car'] = Db::table("store_car")->where(['id'=>$v['car_id']])->find();
            $v['car_tel'] = $v['member']['phone'];

            $v['time'] = strtotime($v['create_at']);
            $v['jiezhi'] = $v['time']+1800;

            $time = time();
            $v['daojishi'] = $v['jiezhi'] - $time;
            if($v['daojishi']<0){
                $v['daojishi'] = 0;
            }

        }

        return $list;

    }



    //余额支付
    public function amount_pay($param){
        $order = self::where(['id'=>$param['order_id']])->find();
        $param['park_price'] = $param['park_price']??0;

        if($order){
            if(empty($order['start_time'])){ return '订单开始时间未录入，暂不能支付，请联系工作人员！'; }
            if(empty($order['end_time'])){ return '订单结束时间未录入，暂不能支付，请联系工作人员！'; }
            $device = Db::table("store_device")->where(['id'=>$order['device_id']])->find();
            $park = Db::table("store_park")->where(['id'=>$order['park_id']])->find();

            $park_time = time()-strtotime($order['start_time']);
            $hour = ceil($park_time/3600);
            $param['park_price'] = sprintf('%.2f',$hour*$park['price']);

            if($order['type']==1){
                $free_park_hour = $device['free_park_hour']??0;
                $free_park_time = $free_park_hour*3600;

                if($free_park_time>$park_time){
                    $param['park_price'] = 0;
                    if($order['charging_capacity']<20){
                        $xiaoshi = ceil($park_time/3600);
                        $param['park_price'] = sprintf('%.2f',$xiaoshi*1);
                    }
                }else{
                    $cha = $park_time-$free_park_time;
                    $xiaoshi = ceil($cha/3600);
                    $param['park_price'] = sprintf('%.2f',$xiaoshi*$park['price']);
                }

                if(empty($order['remark'])){
                    $dev = Db::table("dev")->where(['order_no'=>$order['order_no']])->where("bin_code='3B' or bin_code='3b'")->where("jieguo is not null")->find();
                    if(empty($dev)){
                        return '充电桩结算中 请稍候！！';
                    }else{
                        $electric_price = $order['electric_price'];
                        $service_price = $order['service_price'];
                        $charge_price = sprintf('%.2f',$electric_price+$service_price);
                        Db::table("store_yinuo_order")->where(['id'=>$param['order_id']])->update(['charge_price'=>$charge_price]);
                        $order = self::where(['id'=>$param['order_id']])->find();
                    }
                }


                $total_price = sprintf('%.2f',$param['park_price']+$order['charge_price']);
                self::where(['id'=>$param['order_id']])->update(['park_price'=>$param['park_price'],'total_price'=>$total_price]);
            }else{
                self::where(['id'=>$param['order_id']])->update(['park_price'=>$param['park_price'],'total_price'=>$param['park_price']]);
            }

            $order = self::where(['id'=>$param['order_id']])->find();

            if($order['total_price']<0){ return '支付费用未录入，暂不能支付，请联系工作人员!!'; }

            if($order['status']!=4){  return '订单状态不符，暂不能支付，请联系工作人员！'; }
            if(!empty($order['paid_time'])){  return '订单已支付，请不要重复提交！'; }

            $member = Db::table("store_member")->where(['id'=>$param['member_id']])->find();
            if($member){
                if($member['id']!=$order['member_id']){
                    return '您的账号异常，暂不能支付，请联系工作人员!!';
                }else{
                    if($member['amount']<$order['total_price']){
                        return '您的余额不足，请及时充值!!';
                    }else{
                        $new_amount = $member['amount']-$order['total_price'];
                        Db::table("store_member_amount_log")->insert([
                            'user_id'=>$order['member_id'],
                            'amount'=>$order['total_price'],
                            'before'=>$member['amount'],
                            'after'=>$new_amount,
                            'memo'=>'余额支付',
                            'create_at'=>date('Y-m-d H:i:s'),
                            'lx'=>1,'remark'=>json_encode($order),
                            'is_pay'=>1,'pay_time'=>date('Y-m-d H:i:s')
                        ]);
                        Db::table("store_member")->where(['id'=>$param['member_id']])->update(['amount'=>$new_amount]);
                        self::where(['id'=>$param['order_id']])
                            ->update(['status'=>5,'paid_price'=>$order['total_price'],'paid_time'=>date('Y-m-d H:i:s')]);

                        Db::table("store_device")->where(['id' => $order['device_id']])->update(['status' => 1]);
                        Db::table("store_park")->where(['id' => $order['park_id']])->update(['status' => 1]);
                        Db::table("store_device")->where(['park_id' => $order['park_id']])->update(['status' => 1]);


                        return 1;
                    }
                }
            }else{
                return '您的账号异常，暂不能支付，请联系工作人员！';
            }

        }else{
            return '订单未找到';
        }
    }


    //订单评价
    public function evaluate($param)
    {
        $order = self::where(['id'=>$param['order_id']])->find();
        if($order){
            $member = Db::table("store_member")->where(['id'=>$param['user_id']])->find();
            if($member){
                if($member['id']!=$order['member_id']){
                    return '您的账号异常，暂不能评价，请联系工作人员!!';
                }else{
                    if($order['status']!=5){  return '订单状态不符，暂不能评价，请联系工作人员！'; }
                    $evaluate = $param['evaluate']??4;
                    $evaluate = $evaluate+1;
                    if($evaluate>5){
                        $evaluate = 5;
                    }

                    if($evaluate>3){
                        $type = 1;
                    }elseif($evaluate==3){
                        $type = 2;
                    }else{
                        $type = 3;
                    }

                    Db::table("store_station_comment")->insert([
                        'user_id'=>$order['member_id'],
                        'score'=>$evaluate,
                        'type'=>$type,
                        'order_id'=>$param['order_id'],
                        'station_id'=>$order['station_id'],
                        'comment'=>$param['content']??'',
                        'create_at'=>date('Y-m-d H:i:s'),
                        'images'=>$param['images']??''
                    ]);
                    self::where(['id'=>$param['order_id']])->update(['status'=>6]);
                    return 1;
                }
            }else{
                return '您的账号异常，暂不能评价，请联系工作人员！';
            }
        }else{
            return '订单未找到';
        }
    }

}